/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb.sessionBeans;

import java.security.MessageDigest;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import modelo.Operador;

/**
 *
 * @author inftel
 */
@Stateless
public class OperadorFacade extends AbstractFacade<Operador> implements OperadorFacadeRemote {

    @PersistenceContext(unitName = "TelePaSOS-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public OperadorFacade() {
        super(Operador.class);
    }

    @Override
    public Operador findByLogin(String user, String pass) {
        try {
        return (Operador) em.createQuery("SELECT o FROM Operador o WHERE o.login=:u AND o.password=:p")
                .setParameter("u", user)
                .setParameter("p", md5(pass))
                .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }
    
    /**
     * Devuelve en un string la codificación en md5 de la cadena de entrada.
     *
     * @param cadPass Cadena a codidifcar
     * @return Cadena con la coficación en md5 de la cadena de entrada.
     * @throws java.lang.Exception
     */
    private static String md5(String cadPass) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] b = md.digest(cadPass.getBytes());

            int size = b.length;
            StringBuilder h = new StringBuilder(size);
            for (int i = 0; i < size; i++) {
                int u = b[i] & 255;
                if (u < 16) {
                    h.append("0").append(Integer.toHexString(u));
                } else {
                    h.append(Integer.toHexString(u));
                }
            }
            return h.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}